/*
 * $Id$
 */
package py.windmill.action;

/**
 *
 * @author myang
 */
public class Execution {

    /**
     * 
     * @param rt
     * @param req
     * @return 
     */
    public void execute(final Route rt, final Request req) {

        req.params(rt.parse(req.requestUri()));

        final Resolution resolution = rt.resolution(req);
        req.response().contentType(resolution.produce());

        final Action action = rt.action();
        final ValidationErrors errors = action.validate(req);
        if (null == errors || errors.isEmpty()) {
            resolution.execute(req, execute(action, req));
        }
        else {
            resolution.execute(req, errors);
        }
    }

    /**
     * 
     * @param action
     * @param req
     * @return 
     */
    private Object execute(final Action action, final Request req) {
        if (req.is(HttpMethod.GET)) {
            return action.onGet(req);
        } else if (req.is(HttpMethod.POST)) {
            return action.onPost(req);
        }
        throw new RuntimeException("unsupported method: " + req.method());
    }
}
